window.downloadFile = function(sUrl) {

    //iOS devices do not support downloading. We have to inform user about this.
    if (/(iP)/g.test(navigator.userAgent)) {
        alert('Your device does not support files downloading. Please try again in desktop browser.');
        return false;
    }

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    if (sUrl.indexOf('?') === -1) {
        sUrl += '?download';
    }

    window.open(sUrl, '_self');
    return true;
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
$(function() {


    //轮询
    var timer = null;
    var number = 0;
    timer = window.setInterval(function() {
        $.ajax({
            url: 'http://www.hefatong.com/payment/wx/query/' + ($('input[type=hidden]').val() || 'sadjkasdjkasd'),
            type: 'get',
            success: function(data) {
                var d = JSON.parse(data);
                number++;
                if(number >= 7200){
                    clearInterval(timer);
                }
                if (d.code === 200) {
                    clearInterval(timer);
                    $('.qr-wx').remove();
                    var tpl = [
                        '<div class="dl-wrap">',
                        '<img src="http://www.hefatong.com/img/result/file.png" alt="" />',
                        '<div class="dl-link">下载文档</div>',
                        '</div>'
                    ];
                    $('.qr-wrap').html(tpl.join(''));
                    $('.dl-link').on('click', function() {
                        downloadFile(d.download);
                    });
                }else{
                    console.log(d.message);
                }

            },
            error: function(err) {
                console.log('网络错误!');
            }
        });
    }, 2000);

});